<?php
include ("../includes/config.php");
include ("../includes/functions.php");
connect ();
$action=$_POST['action'];
$pattern['uname']='/^([a-z]|[A-Z]|[0-9])*$/';
$pattern['email']='/^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/';
switch ($action) {
case 'signup':
	$uname=$_POST['uname'];
	$pass=$_POST['pass'];
	$email=$_POST['email'];
	if ((!$uname)||(!$pass)||(!$email)) {
		$arr=array("successful"=>"false", "message"=>"Something is empty. <3 XSS");
	}else if ((strlen($uname)>20)||(strlen($pass)>20)||(strlen($email)>30)) {
		$arr=array("successful"=>"false", "message"=>"Something is too big! Yes. Size does matter.");
	}else if (preg_match($pattern['uname'], $uname)!=1) {
		$arr=array("successful"=>"false", "message"=>"Invalid username!!");
	}else if (preg_match($pattern['email'], $email)!=1) {
		$arr=array("successful"=>"false", "message"=>"Invalid email!!");
	}else {
		if (value_exists ($uname, 'uname', 'users')) {
			$arr=array("successful"=>"false", "message"=>"Username Exists!");
		}else if (value_exists ($email, 'email', 'users')) {
			$arr=array("successful"=>"false", "message"=>"Email Exists!");
		}else{
			$uid=register_user($uname, $pass, $email);
			if ($uid>0) {
				$arr=array("successful"=>"true", "uid"=>"$uid");
			}else{
				$arr=array("successful"=>"false", "message"=>"Ooops! Something went wrong with your registration!");
			}
		}
	}
break;
case 'login':
	$uname=$_POST['uname'];
	$pass=$_POST['pass'];
	$arr=check_credentials ($uname, $pass);
	if ($arr['successful']=='true') {
		$uid=$arr['uid'];
		if (!login_user ($uid, $uname, $pass)) {
			$arr=array("successful"=>"false", "message"=>"Unexpected Error : Could not log in!");
			logout_user ();
		}
	}else{
		logout_user ();
	}
break;
case 'logout':
	if (logout_user ()) {
		$arr=array("successful"=>"true");
	}else{
		$arr=array("successful"=>"false", "message"=>"Unexpected Error : Could not log out!");
	}
break;
}

header("Content-type: application/json; charset:UTF-8");
echo json_encode ($arr);
?>
